// app.js
import MPServerless from './miniprogram_npm/@alicloud/mpserverless-sdk/index.js';

const mpserverless = new MPServerless(wx,
  {
    appId: 'wxbc3cce50edc7a575', // 小程序应用标识
    spaceId: 'mp-f3b68706-562e-4e88-9436-5e8c05efc576', // 服务空间标识
    clientSecret: 'WLikPuqJXqwn0e5fWvtZQA==', // 服务空间 secret key
    endpoint: 'https://api.next.bspapp.com', // 服务空间地址，从小程序 serverless 控制台处获得
  });

App({
  mpserverless: mpserverless,
  onLaunch() {
    const that = this;
    mpserverless.init();
    // 获取用户是否已经授权
    wx.getStorage({
      key: 'Authorized',
      success: (result) => {
        that.globalData.isAuthorized = result.data.isAuthorized;
      }
    });

    // 登录获取code并调用云函数获取openId
    wx.login({
      timeout: 3000,
      success: res => {
        let login_code = res.code;
        mpserverless.function.invoke('getOpenId', {
          code: login_code
        }).then((res) => {
          that.globalData.openId = res.result;

          mpserverless.db.collection('userInfo').find({openId:res.result}).then(e=>{
            if (e.result == '') {
              that.globalData.isAuthorized = false;
              //将已授权存储到storage里面
              wx.setStorage({
                key: 'Authorized',
                data: {
                  isAuthorized: false
                }
              });
            } else {
              that.globalData.isAuthorized = true;
              that.globalData.userInfo = e.result[0].userInfo;
              //将用户信息存储到storage里面
              wx.setStorage({
                key: 'userInfo',
                data: {
                  userInfo: e.result[0].userInfo
                }
              });
              //将已授权存储到storage里面
              wx.setStorage({
                key: 'Authorized',
                data: {
                  isAuthorized: true
                }
              });
            }
          });

          if(that.openidCallback){
            that.openidCallback(res.result);
          }
        }).catch(console.error);
      },
      fail: (e) => { Toast.fail('服务器出错啦！') },
    })
  },

  globalData: {
    userInfo: null,  //用户信息
    isFreash: true,   //是否需要更新页面数据
    openId: '',       //用户身份证
    isAuthorized: false,  //用户是否授权
  }
})
